<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" class="search-bar-form" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="name">
          <el-input v-model="queryParams.name" placeholder="菜单名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><ep-Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><ep-Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="handleOpenDialog()">
          <template #icon><ep-Plus /></template>
          新增
        </el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="menuTableData?.result || []"
        border
        highlight-current-row
        row-key="id"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren'
        }"
      >
        <el-table-column label="菜单名称" min-width="200">
          <template #default="scope">
            <template v-if="scope.row.icon && !scope.row.icon.startsWith('ep-') && !scope.row.icon.startsWith('ad-')">
              <svg-icon :name="scope.row.icon" />
            </template>
            <template v-else-if="scope.row.icon">
              <el-icon style="vertical-align: -0.15em">
                <component :is="scope.row.icon" />
              </el-icon>
            </template>
            <template v-else-if="scope.row.type !== MenuTypeEnum.BUTTON">
              <svg-icon name="menu" />
            </template>

            <!-- <template v-if="scope.row.type !== MenuTypeEnum.BUTTON">
              <el-icon style="vertical-align: -0.15em">
                <component :is="scope.row.icon || `ep-Menu`" />
              </el-icon>
            </template> -->
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.type === MenuTypeEnum.CATALOG" type="warning">目录</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.MENU" type="success">菜单</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.BUTTON" type="danger">按钮</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.EXTLINK" type="info">外链</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="路由名称" align="left" width="150" prop="routeName" />
        <el-table-column label="路由路径" align="left" width="150" prop="path" />
        <el-table-column label="组件路径" align="left" width="250" prop="component" />
        <el-table-column label="权限标识" align="center" width="200" prop="permission" />
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.visible === 1" type="success">显示</el-tag>
            <el-tag v-else type="info">隐藏</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="80" prop="sortOrder" />
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.type == MenuTypeEnum.CATALOG || scope.row.type == MenuTypeEnum.MENU"
              type="primary"
              link
              size="small"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              <template #icon><ep-Plus /></template>
              新增
            </el-button>

            <el-button type="primary" link size="small" @click.stop="handleOpenDialog(undefined, scope.row)">
              <template #icon><ep-Edit /></template>
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click.stop="handleDelete(scope.row.id)">
              <template #icon><ep-Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-drawer v-model="drawer.visible" :title="drawer.title" size="50%" @close="handleCloseDialog">
      <el-form ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级菜单"
            :data="menuOptions"
            filterable
            check-strictly
            show-checkbox
            :render-after-expand="false"
            :props="{ label: 'label' }"
          />
        </el-form-item>

        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type" @change="handleMenuTypeChange">
            <el-radio :value="MenuTypeEnum.CATALOG">目录</el-radio>
            <el-radio :value="MenuTypeEnum.MENU">菜单</el-radio>
            <el-radio :value="MenuTypeEnum.BUTTON">按钮</el-radio>
            <el-radio :value="MenuTypeEnum.EXTLINK">外链</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.type === MenuTypeEnum.EXTLINK" label="外链地址" prop="path">
          <el-input v-model="formData.path" placeholder="请输入外链完整路径" />
        </el-form-item>

        <el-form-item v-if="formData.type === MenuTypeEnum.CATALOG || formData.type === MenuTypeEnum.MENU" prop="path">
          <template #label>
            <div class="flex-y-c">
              路由路径
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  定义应用中不同页面对应的 URL 路径，目录需以 / 开头，菜单项不用。例如：系统管理目录 /system，系统管理下的用户管理菜单
                  user。
                </template>
                <el-icon class="ml-4 cursor-pointer">
                  <ep-QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="formData.path" placeholder="user">
            <template v-if="formData.type === MenuTypeEnum.CATALOG" #prepend>/</template>
          </el-input>
        </el-form-item>

        <el-form-item v-if="formData.type === MenuTypeEnum.MENU" prop="routeName">
          <template #label>
            <div class="flex-y-c">
              路由名称
              <el-tooltip placement="bottom" effect="light">
                <template #content>如果需要开启缓存，需保证页面 defineOptions 中的 name 与此处一致，建议使用驼峰。</template>

                <el-icon class="ml-4 cursor-pointer">
                  <ep-QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="formData.routeName" placeholder="User" />
        </el-form-item>

        <el-form-item v-if="formData.type === MenuTypeEnum.MENU" prop="component">
          <template #label>
            <div class="flex-y-c">
              组件路径
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  组件页面完整路径，相对于 src/views/，如 system/user/index，缺省后缀 .vue
                  <br />
                  注意：如果当前菜单是父级菜单，请固定填写 RouterView
                </template>
                <el-icon class="ml-4 cursor-pointer">
                  <ep-QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>

          <el-input v-model="formData.component" placeholder="system/user/index" style="width: 95%">
            <template #prepend>src/views/</template>
            <template #append>.vue</template>
          </el-input>
        </el-form-item>

        <el-form-item v-if="formData.type !== MenuTypeEnum.BUTTON" prop="visible" label="显示状态">
          <el-radio-group v-model="formData.visible">
            <el-radio :value="1">显示</el-radio>
            <el-radio :value="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.type === MenuTypeEnum.CATALOG || formData.type === MenuTypeEnum.MENU">
          <template #label>
            <div class="flex-y-c">
              始终显示
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  选择“是”，即使目录或菜单下只有一个子节点，也会显示父节点。
                  <br />
                  选择“否”，如果目录或菜单下只有一个子节点，则只显示该子节点，隐藏父节点。
                  <br />
                  如果是叶子节点，请选择“否”。
                </template>
                <el-icon class="ml-4 cursor-pointer">
                  <ep-QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>

          <el-radio-group v-model="formData.alwaysShow">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.type === MenuTypeEnum.MENU" label="缓存页面">
          <el-radio-group v-model="formData.keepAlive">
            <el-radio :value="1">开启</el-radio>
            <el-radio :value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="formData.sortOrder" style="width: 100px" controls-position="right" :min="0" />
        </el-form-item>

        <!-- 权限标识 -->
        <el-form-item v-if="formData.type === MenuTypeEnum.BUTTON" label="权限标识" prop="permission">
          <el-input v-model="formData.permission" placeholder="sys_user_add" />
        </el-form-item>

        <el-form-item v-if="formData.type !== MenuTypeEnum.BUTTON" label="图标" prop="icon">
          <!-- 图标选择器 -->
          <icon-select v-model="formData.icon" />
        </el-form-item>

        <el-form-item v-if="formData.type === MenuTypeEnum.CATALOG" label="跳转路由">
          <el-input v-model="formData.redirect" placeholder="跳转路由" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { MenuTypeEnum } from '@/enums/MenuTypeEnum'
import { getTreeByParentId, queryMenuAndTable, addMenu, updateMenu, removeMenu } from '@/api/system/menu'
import { useRequest } from '@/hooks/useRequest'
import type { MenuForm, MenuData } from '@/api/system/menu'

const queryFormRef = ref(ElForm)
const menuFormRef = ref(ElForm)

const queryParams = reactive<{ name?: string }>({})
const menuOptions = ref<OptionType[]>([])

const drawer = reactive({
  title: '新增菜单',
  visible: false
})

// 初始菜单表单数据
const initialMenuFormData = ref<MenuForm>({
  id: undefined,
  parentId: '0',
  alwaysShow: 0,
  visible: 1,
  sortOrder: 1,
  type: MenuTypeEnum.MENU, // 默认菜单
  keepAlive: 1
})

// 菜单表单数据
const formData = ref<MenuForm>({ ...initialMenuFormData.value })

// 表单验证规则
const rules = reactive({
  parentId: [{ required: true, message: '请选择顶级菜单', trigger: 'blur' }],
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择菜单类型', trigger: 'blur' }],
  routeName: [{ required: true, message: '请输入路由名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
  component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
  visible: [{ required: true, message: '', trigger: 'blur' }]
})

const { data: menuTableData, run, loading } = useRequest(getTreeByParentId)

const handleQuery = () => {
  run(queryParams)
}

const handleResetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/**
 * 打开表单弹窗
 */
const handleOpenDialog = async (parentId = '0', row?: MenuData) => {
  const res = await queryMenuAndTable()
  menuOptions.value = [{ value: '0', label: '根目录', children: res.result || [] }]
  drawer.visible = true
  if (row) {
    drawer.title = '编辑菜单'
    const menuForm = { ...row, path: row.path ? row.path.replace(/\//g, '') : '' }
    delete menuForm.children
    formData.value = { ...menuForm }
  } else {
    drawer.title = '新增菜单'
    formData.value.parentId = parentId
  }
}

const submitForm = () => {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formData.value.id
      if (formData.value.type === MenuTypeEnum.CATALOG) {
        formData.value.component = 'Layout'
        formData.value.path = '/' + formData.value.path
      }
      if (menuId) {
        formData.value.menuId = menuId
        updateMenu(formData.value).then(() => {
          ElMessage.success('修改成功')
          handleCloseDialog()
          handleQuery()
        })
      } else {
        addMenu(formData.value).then(() => {
          ElMessage.success('新增成功')
          handleCloseDialog()
          handleQuery()
        })
      }
    }
  })
}

const handleCloseDialog = () => {
  drawer.visible = false
  menuFormRef.value.resetFields()
  menuFormRef.value.clearValidate()
  // formData.value.id = undefined
  formData.value = { ...initialMenuFormData.value }
}

const handleDelete = (id: string) => {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    removeMenu(id).then(() => {
      ElMessage.success('删除成功')
      handleQuery()
    })
  })
}

// 菜单类型切换
const handleMenuTypeChange = () => {
  // 如果菜单类型改变
  // if (formData.value.type !== initialMenuFormData.value.type) {
  //   if (formData.value.type === MenuTypeEnum.MENU) {
  //     // 目录切换到菜单时，清空组件路径
  //     if (initialMenuFormData.value.type === MenuTypeEnum.CATALOG) {
  //       formData.value.component = ''
  //     } else {
  //       // 其他情况，保留原有的组件路径
  //       formData.value.path = initialMenuFormData.value.path
  //       formData.value.component = initialMenuFormData.value.component
  //     }
  //   }
  // }
}
</script>
<style lang="scss" scoped></style>
